package com.gitee.wsl.struct.grammar.ext

import com.gitee.wsl.struct.grammar.GrammarContext
import com.gitee.wsl.struct.grammar.parser.Parser
import com.gitee.wsl.struct.grammar.parser.combinator.ChoiceParser
import com.gitee.wsl.struct.grammar.parser.combinator.TupleParser
import com.gitee.wsl.struct.grammar.parser.combinator.and
import com.gitee.wsl.struct.grammar.parser.token.literalToken

fun <T : Any> GrammarContext.choice(vararg p: Parser<T>): Parser<T> = ChoiceParser(p.toList())

fun <T : Any> GrammarContext.seq(vararg p: Any,transform: (List<Any?>) -> T): Parser<T> = TupleParser(
    p.map {
                when(it) {
                    Char, String -> literalToken(it.toString())
                    is Parser<*> -> it
                }
               } as List<Parser<Any>>
    ,transform
)

fun <T : Any> GrammarContext.seq(before:Char, p: Parser<T>,after:Char) = seq(before.toString(),p,after.toString())

fun <T : Any> GrammarContext.seq(before:String, p: Parser<T>,after:String) = literalToken(before) and p and literalToken(after)